<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>封装-简易axios函数-注册账号</title>
  </head>
  <body>
    <h2>封装-简易axios函数-注册账号</h2>
    <button class="btn">注册用户</button>
    <script>
      // 封装-简易axios函数-注册账号
      function myAxios(config) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest()

          if (config.params) {
            const params = new URLSearchParams(config.params)
            const query = params.toString()
            config.url += `?${query}`
          }
          xhr.open(config.method || 'GET', config.url)

          xhr.addEventListener('loadend', () => {
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(JSON.parse(xhr.response))
            } else {
              reject(new Error(xhr.response))
            }
          })
          // 1. 判断data属性
          if (config.data) {
            // 2. 设置请求头
            xhr.setRequestHeader('Content-Type', 'application/json')
            // 3. 请求体携带数据 JS对象-》JSON
            xhr.send(JSON.stringify(config.data))
          } else {
            // 请求体不需要携带数据时调用
            xhr.send()
          }
        })
      }
      document.querySelector('.btn').addEventListener('click', () => {
      // 4.调用函数实现功能
      myAxios({
        url: 'http://hmajax.itheima.net/api/register',
        method: 'POST',
        data: {
          username: 'dingxiaodou666',
          password: '123456'
        }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.dir(err)
      })
    })
    </script>
  </body>
</html>
